package Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class p257二叉树的所有路径 {
    class Solution {
        LinkedList<String> list = new LinkedList<>();
        ArrayList<Integer> nodeList = new ArrayList<>();

        public List<String> binaryTreePaths(TreeNode root) {
            if (root == null) return list;
            getPath(root);
            return list;
        }

        public void getPath(TreeNode node) {
            nodeList.add(node.val);
            if (node.left == null && node.right == null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < nodeList.size() - 1; i++) {
                    sb.append(nodeList.get(i));
                    sb.append("->");
                }
                sb.append(nodeList.get(nodeList.size() - 1));
                list.add(sb.toString());
                return;
            }
            if (node.left != null) {
                getPath(node.left);
                nodeList.remove(nodeList.size() - 1);
            }
            if (node.right != null){
                getPath(node.right);
                nodeList.remove(nodeList.size() - 1);
            }
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
